// CropOverlay.tsx
// 说明：画布级别的可旋转裁剪框组件
// 功能：
// - 在画布上显示可拖拽/缩放/旋转的裁剪框（UI + 事件抛出）
// - 不包含真正的裁剪逻辑，只负责交互与样式，将事件回调给父组件处理
// - 采用绝对定位并使用高 z-index，确保覆盖在画布元素之上

import React from 'react'
import { View, Button } from '@tarojs/components'

type Box = { x: number; y: number; w: number; h: number }

type Props = {
  box: Box
  angle: number
  onBoxDown: (ev: any) => void
  onHandleDown: (handle: string, ev: any) => void
  onCancel: () => void
  onConfirm: () => void
}

// 该组件不保存内部状态，所有变更由父组件驱动，便于测试与状态集中管理
const CropOverlay: React.FC<Props> = ({ box, angle, onBoxDown, onHandleDown, onCancel, onConfirm }) => {
  const hs = 12
  const boxStyle: any = {
    position: 'absolute',
    left: box.x,
    top: box.y,
    width: box.w,
    height: box.h,
    border: '2px dashed #4aa',
    boxSizing: 'border-box',
    pointerEvents: 'auto',
    zIndex: 9999,
    transform: `rotate(${angle || 0}deg)`,
    transformOrigin: 'center'
  }

  const handleCommon: any = { position: 'absolute', width: hs, height: hs, background: '#4aa', borderRadius: 2 }

  return (
    <View style={boxStyle} onTouchStart={onBoxDown}>
      {/* 角点缩放句柄 */}
      <View onTouchStart={(e: any) => onHandleDown('nw', e)} style={{ ...handleCommon, left: -hs / 2, top: -hs / 2 }} />
      <View onTouchStart={(e: any) => onHandleDown('ne', e)} style={{ ...handleCommon, right: -hs / 2, top: -hs / 2 }} />
      <View onTouchStart={(e: any) => onHandleDown('sw', e)} style={{ ...handleCommon, left: -hs / 2, bottom: -hs / 2 }} />
      <View onTouchStart={(e: any) => onHandleDown('se', e)} style={{ ...handleCommon, right: -hs / 2, bottom: -hs / 2 }} />

      {/* 旋转句柄（顶部中间） */}
      <View onTouchStart={(e: any) => onHandleDown('rot', e)} style={{ position: 'absolute', left: '50%', top: -32, marginLeft: -8, width: 16, height: 16, borderRadius: 16, background: '#4aa' }} />

      {/* 操作按钮 */}
      <View style={{ position: 'absolute', right: -8, bottom: -36, display: 'flex', flexDirection: 'row' }}>
        <Button onClick={onCancel} style={{ padding: '4px 8px', background: '#fff', borderRadius: 4, marginRight: 6 }}>取消</Button>
        <Button onClick={onConfirm} style={{ padding: '4px 8px', background: '#4aa', color: '#fff', borderRadius: 4 }}>确认</Button>
      </View>
    </View>
  )
}

export default CropOverlay


